package cn.tedu.csmall.product.service.impl;

import cn.tedu.csmall.product.mapper.BrandCategoryMapper;
import cn.tedu.csmall.product.mapper.CategoryAttributeTemplateMapper;
import cn.tedu.csmall.product.mapper.CategoryMapper;
import cn.tedu.csmall.product.mapper.SpuMapper;
import cn.tedu.csmall.product.pojo.entity.BrandCategory;
import cn.tedu.csmall.product.pojo.entity.Category;
import cn.tedu.csmall.product.pojo.entity.CategoryAttributeTemplate;
import cn.tedu.csmall.product.pojo.entity.SPU;
import cn.tedu.csmall.product.pojo.param.CategoryAddNewParam;
import cn.tedu.csmall.product.pojo.param.CategoryUpdateInfoParam;
import cn.tedu.csmall.product.pojo.vo.CategoryListItemVO;
import cn.tedu.csmall.product.pojo.vo.CategoryStandardVO;
import cn.tedu.csmall.product.pojo.vo.CategoryTreeItemVO;
import cn.tedu.csmall.product.service.ICategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.csmall.commons.ex.ServiceException;
import com.example.csmall.commons.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class CategoryServiceImpl implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandCategoryMapper brandCategoryMapper;
    @Autowired
    private CategoryAttributeTemplateMapper categoryAttributeTemplateMapper;
    @Autowired
    private SpuMapper spuMapper;

    @Override
    public void addNew(CategoryAddNewParam categoryAddNewParam) {
        // 调用参数对象的getName()得到尝试添加的类别的名称和父类ID
        String name = categoryAddNewParam.getName();
        Long parentId= categoryAddNewParam.getParentId();
        // 调用Mapper对象的countByName()执行统计查询
        int countByName = categoryMapper.countByName(name, parentId);
        log.debug("根据名称【{}】、父类ID【{}】统计数量，结果：{}", name, parentId, countByName);
        // 判断结果是否大于0
        if (countByName > 0) {
            String message = "添加类别失败，同父级下类别名称已存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        
        // 调整当前类的depth深度值
        // 预设当前depth深度值为1
        Integer depth = 1;
        CategoryStandardVO parentCategory = null;
        // 判断parentId是否为0，如果为0则默认为深度1，如果不为0使用父类ID查询当前类别的父类后对本类别深度进行修改
        if (parentId != 0) {
            parentCategory = categoryMapper.getStandardById(parentId);
            // 判断查询到的父类是否为null，是null添加失败
            if (parentCategory == null) {
                // 是，抛出不存在异常！
                String message = "添加类别失败，父级类别不存在！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
            } else {
                // 否，当前类的depth为父类 ＋ 1 
                depth = parentCategory.getDepth() + 1;
            }
        }
        
        // 新增该类别
        Category category = new Category();
        BeanUtils.copyProperties(categoryAddNewParam, category);
        // 补全当前类别的属性值：depth
        category.setDepth(depth);
        // 补全当前类别的isParent，初始化为0
        category.setIsParent(0);
        // insert该类别
        int rows = categoryMapper.insert(category);
        if (rows != 1) {
            String message = "添加类别失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }

        // 修改当前类的父类的isParent值
        if (parentId != 0 && parentCategory.getIsParent() == 0) {
            Category updateParentCategory = new Category();
            updateParentCategory.setId(parentId);
            updateParentCategory.setIsParent(1);
            rows = categoryMapper.updateById(updateParentCategory);
            if (rows != 1) {
                String message = "添加类别失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理【根据ID删除类别】的业务,参数:{}", id);
        // 调用Mapper对象的getStandardById()执行查询
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null，如果是则抛出异常
        if (currentCategory == null) {
            String message = "删除类别失败，当前类别不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的isParent是否为1，如果是，则抛出异常
        if (currentCategory.getIsParent() == 1) {
            String message = "删除类别失败，当前类别包含子级类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 检查是否有品牌和类别关联到此类别，如果存在则抛出异常
        QueryWrapper<BrandCategory> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("category_id", id);
        int countByCategoryId2= brandCategoryMapper.selectCount(queryWrapper2);
        log.debug("根据类别ID统计匹配的品牌和类别的数量,结果:{}", countByCategoryId2);
        if (countByCategoryId2 > 0) {
            String message = "删除类别失败，仍有品牌和类别关联到此类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        // 检查是否有类别和属性关联到此类别，如果存在则抛出异常
        QueryWrapper<CategoryAttributeTemplate> queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("category_id", id);
        int countByCategoryId5 = categoryAttributeTemplateMapper.selectCount(queryWrapper5);
        log.debug("根据类别ID统计匹配的属性和类别关联数量,结果:{}", countByCategoryId5);
        if (countByCategoryId5 > 0) {
            String message = "删除类别失败，仍有属性和类别关联到此类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        // 检查是否有SPU关联到此类别，如果存在则抛出异常
        QueryWrapper<SPU> queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("category_id", id);
        int countByCategoryId4 = spuMapper.selectCount(queryWrapper4);
        log.debug("根据类别ID统计匹配的SPU数量,结果:{}", countByCategoryId4);
        if (countByCategoryId4 > 0) {
            String message = "删除类别失败，仍有SPU关联到此类别！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 执行删除类别
        log.debug("开始删除类别, ID:" + id);
        int rows = categoryMapper.deleteById(id);
        if (rows != 1) {
            String message = "删除类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("根据ID删除类别完成!");

        // 根据删除类的parentId判断是否需要修改父类的isParent属性
        Long parentId = currentCategory.getParentId();
        log.debug("parentId:{}",parentId);
        int countByParentId = categoryMapper.countByParentId(parentId);
        // 判断统计结果是否为0，true则将父类的isParent属性值改为0
        log.debug("查询到的统计数量：{}",countByParentId);
        if (countByParentId == 0) {
            Category parentCategory = new Category();
            parentCategory.setId(parentId);
            parentCategory.setIsParent(0);
            rows = categoryMapper.updateById(parentCategory);
            log.warn("修改完成!");
            if (rows != 1) {
                String message = "添加类别失败，服务器忙，请稍后再试！";
                log.warn(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }

    }

    @Override
    public CategoryStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询类别详情】的业务，参数：{}", id);
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        if (queryResult == null) {
            // 是：抛出异常
            String message = "查询类别详情失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public List<CategoryListItemVO> listByParentId(Long parentId) {
        log.debug("开始处理【获取子类列表】的业务，参数：父类ID{}", parentId);
        List<CategoryListItemVO> categoryList = categoryMapper.listByParentId(parentId);
        return categoryList;
    }


    @Override
    public void update(Long id, CategoryUpdateInfoParam categoryUpdateInfoParam) {
        log.debug("开始处理【修改类别详情】的业务，ID：{}，新数据：{}", id, categoryUpdateInfoParam);
        // 调用Mapper对象的getStandardById()执行查询
        CategoryStandardVO queryResult = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null
        if (queryResult == null) {
            // 是：抛出异常
            String message = "修改类别详情失败，尝试修改的类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 调用Mapper对象的countByNameAndNotId()执行统计
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", categoryUpdateInfoParam.getName()).ne("id", id);
        int countByName = categoryMapper.selectCount(queryWrapper);
        log.debug("根据类别名称统计匹配的类别的数量，结果：{}", countByName);
        if (countByName > 0) {
            String message = "修改类别详情失败，类别名称已经被占用！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建Category对象
        Category category = new Category();
        // 复制属性，设置ID
        BeanUtils.copyProperties(categoryUpdateInfoParam, category);
        category.setId(id);
        // 调用Mapper对象的update()方法执行修改
        int rows = categoryMapper.updateById(category);
        if (rows != 1) {
            String message = "修改类别详情失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void setEnable(Long id) {
        log.debug("开始处理【启用类别】的业务，参数：{}", id);
        updateEnableById(id, 1);
    }

    @Override
    public void setDisable(Long id) {
        log.debug("开始处理【禁用类别】的业务，参数：{}", id);
        updateEnableById(id, 0);
    }

    // 启用类别
    private void updateEnableById(Long id, Integer enable) {
        // 调用Mapper对象的getStandardById()方法执行查询
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null，如果是则抛出异常
        if (currentCategory == null) {
            String message = ENABLE_TEXT[enable] + "类别失败，类别数据不存在！";
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的enable与参数enable是否相同，如果是，抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (currentCategory.getEnable() == enable) {
            String message = ENABLE_TEXT[enable] + "类别失败，此类别已经处于" + ENABLE_TEXT[enable] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        // 创建Category对象
        Category updateCategory = new Category();
        // 向对象中封装属性值：id, enable, 均来自方法参数
        updateCategory.setId(id);
        updateCategory.setEnable(enable);
        // 调用对象的uodate() 方法执行更新
        int rows = categoryMapper.updateById(updateCategory);
        if (rows != 1) {
            String message = ENABLE_TEXT[enable] + "类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public void setDisplay(Long id) {
        log.debug("开始处理【将类别显示在导航栏】的业务，参数：{}", id);
        updateDisplayById(id, 1);
    }

    @Override
    public void setHidden(Long id) {
        log.debug("开始处理【将类别不显示在导航栏】的业务，参数：{}", id);
        updateDisplayById(id, 0);
    }

    private void updateDisplayById(Long id, Integer isDisplay) {
        // 调用Mapper对象的getStandardById()方法执行查询
        CategoryStandardVO currentCategory = categoryMapper.getStandardById(id);
        // 判断查询结果是否为null，如果是，则抛出异常
        if (currentCategory == null) {
            String message = DISPLAY_TEXT[isDisplay] + "类别失败，类别数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        // 判断查询结果中的isDisplay与参数isDisplay是否相同，如果是，则抛出异常（当前状态与目标状态相同，没必要执行更新）
        if (currentCategory.getIsDisplay() == isDisplay) {
            String message = DISPLAY_TEXT[isDisplay] + "类别失败，此类别已经处于" + DISPLAY_TEXT[isDisplay] + "状态！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }
        // 创建Category对象
        Category updateCategory = new Category();
        // 向Category对象中封装属性值：id, isDisplay，均来自方法参数
        updateCategory.setId(id);
        updateCategory.setIsDisplay(isDisplay);
        // 执行对象的updateById()方法执行更新
        int rows = categoryMapper.updateById(updateCategory);
        if (rows != 1) {
            String message = DISPLAY_TEXT[isDisplay] + "类别失败，服务器忙，请稍后再尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }

    }

    @Override
    public List<CategoryTreeItemVO> listTree() {
        log.debug("开始处理【获取类别树】的业务");
        List<CategoryTreeItemVO> categoryTree = new ArrayList<>();

        List<CategoryListItemVO> categoryList = categoryMapper.list();
        Map<Long, CategoryListItemVO> allCategoryMap = transformListToMap(categoryList);
        for (Long key : allCategoryMap.keySet()) {
            CategoryListItemVO mapItem = allCategoryMap.get(key);
            if (mapItem.getParentId() == 0) {
                CategoryTreeItemVO categoryTreeItemVO = convertListItemToTreeItem(mapItem);
                categoryTree.add(categoryTreeItemVO);

                fillChildren(mapItem, categoryTreeItemVO, allCategoryMap);
            }
        }
        return categoryTree;
    }

    private Map<Long, CategoryListItemVO> transformListToMap(List<CategoryListItemVO> categoryList) {
        Map<Long, CategoryListItemVO> categoryMap = new LinkedHashMap<>();
        for (CategoryListItemVO categoryListItemVO : categoryList) {
            if (categoryListItemVO.getEnable() == 0) {
                continue;
            }
            categoryMap.put(categoryListItemVO.getId(), categoryListItemVO);
        }
        return categoryMap;
    }

    private void fillChildren(CategoryListItemVO listItem, CategoryTreeItemVO currentTreeItem, Map<Long, CategoryListItemVO> allCategoryMap) {
        if (listItem.getIsParent() == 1) {
            currentTreeItem.setChildren(new ArrayList<>());
            Set<Long> keySet = allCategoryMap.keySet();
            for (Long key : keySet) {
                CategoryListItemVO mapItem = allCategoryMap.get(key);
                if (mapItem.getParentId() == listItem.getId()) {
                    CategoryTreeItemVO categoryTreeSubItemVO = convertListItemToTreeItem(mapItem);
                    currentTreeItem.getChildren().add(categoryTreeSubItemVO);
                    if (mapItem.getIsParent() == 1) {
                        fillChildren(mapItem, categoryTreeSubItemVO, allCategoryMap);
                    }
                }
            }
        }
    }

    private CategoryTreeItemVO convertListItemToTreeItem(CategoryListItemVO listItem) {
        return new CategoryTreeItemVO().setValue(listItem.getId()).setLabel(listItem.getName());
    }

}
